package com.wngbms.homework._02;

import java.io.*;

public class CustomerClassloader extends ClassLoader {

    public static void main(String[] args) throws FileNotFoundException, ClassNotFoundException, IllegalAccessException, InstantiationException {
        Object hello = new CustomerClassloader().findClass("Hello").newInstance();
        System.out.println(hello);
        System.out.println(hello.getClass().getName());
        System.out.println(hello.getClass().getTypeName());
        System.out.println(hello.getClass().getClassLoader());
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        try {
            byte[] bytes = decode();
            return defineClass(name, bytes, 0 , bytes.length);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static byte[] decode() throws IOException {
        FileInputStream fis = new FileInputStream("src/com/wngbms/homework/_02/Hello.xlass");
        byte[] buf = new byte[1024];
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        int len = 0;
        while ((len = fis.read(buf)) > 0) {
            handle(buf, len);
            bos.write(buf, 0, len);
        }

        return bos.toByteArray();
    }

    public static void handle(byte[] buf, int len) {
        for (int i = 0; i < len; i++) {
            buf[i] = (byte) (255 - buf[i]);
        }
    }

}
